from flask import Blueprint, render_template, request, jsonify, redirect, url_for, session
from app.services.movie_service import MovieService
from app.services.user_service import UserService
from flask_login import login_required, current_user

# 创建蓝图
movies_admin_bp = Blueprint('movies_admin', __name__, url_prefix='/admin/movies')

# 管理员权限验证装饰器
def admin_required(view_func):
    def wrapped_view(*args, **kwargs):
        if not current_user.is_authenticated:
            return redirect(url_for('auth.login', next=request.url))
        
        if not current_user.is_admin:
            return jsonify({"success": False, "message": "需要管理员权限"}), 403
            
        return view_func(*args, **kwargs)
    wrapped_view.__name__ = view_func.__name__
    return wrapped_view

@movies_admin_bp.route('/')
@admin_required
def index():
    """影视资源管理首页"""
    movies = MovieService.get_all_movies()
    return render_template('admin/movies.html', movies=movies)

@movies_admin_bp.route('/create', methods=['POST'])
@admin_required
def create():
    """创建影视资源"""
    try:
        data = request.form
        # 基本验证
        if not data.get('name') or not data.get('url'):
            return jsonify({"success": False, "message": "资源名称和URL不能为空"}), 400
            
        # 处理表单数据
        form_data = dict(data)
        
        # 处理复选框
        form_data['is_active'] = 'true' if data.get('is_active') == 'on' else 'false'
            
        # 创建影视资源
        MovieService.create_movie(form_data)
        
        return jsonify({"success": True, "message": "影视资源创建成功"})
    except ValueError as e:
        return jsonify({"success": False, "message": str(e)}), 400
    except Exception as e:
        return jsonify({"success": False, "message": f"创建影视资源失败: {str(e)}"}), 500

@movies_admin_bp.route('/update/<int:movie_id>', methods=['POST'])
@admin_required
def update(movie_id):
    """更新影视资源信息"""
    try:
        data = request.form
        
        # 处理表单数据
        form_data = {
            'name': data.get('name'),
            'desc': data.get('desc'),
            'url': data.get('url'),
            'play_url': data.get('play_url'),
            'is_active': 'true' if data.get('is_active') == 'true' else 'false'
        }
        
        # 更新影视资源
        MovieService.update_movie(movie_id, form_data)
        
        return jsonify({"success": True, "message": "影视资源更新成功"})
    except ValueError as e:
        return jsonify({"success": False, "message": str(e)}), 404
    except Exception as e:
        return jsonify({"success": False, "message": f"更新影视资源失败: {str(e)}"}), 500

@movies_admin_bp.route('/delete/<int:movie_id>', methods=['POST'])
@admin_required
def delete(movie_id):
    """删除影视资源"""
    try:
        # 删除影视资源
        MovieService.delete_movie(movie_id)
        
        return jsonify({"success": True, "message": "影视资源删除成功"})
    except ValueError as e:
        return jsonify({"success": False, "message": str(e)}), 404
    except Exception as e:
        return jsonify({"success": False, "message": f"删除影视资源失败: {str(e)}"}), 500

@movies_admin_bp.route('/get/<int:movie_id>', methods=['GET'])
@admin_required
def get_movie(movie_id):
    """获取单个影视资源信息"""
    try:
        movie = MovieService.get_movie_by_id(movie_id)
        if not movie:
            return jsonify({"success": False, "message": "影视资源不存在"}), 404
            
        return jsonify({
            "success": True,
            "movie": movie.to_dict()
        })
    except Exception as e:
        return jsonify({"success": False, "message": f"获取影视资源信息失败: {str(e)}"}), 500 